package sample.three;



import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;






/**
 * <p>
 * <a href="RunTask.java.html"><i>View Source</i></a>
 * </p>
 *
 * @author 5jxiang
 * @version $Id$
 */
public class RunTask implements Delayed,Runnable {
	
	
	protected int priority = 0;
	
	protected long delayedMilliseconds = 0;
	private String name;
	
	public void setPriority(int priority) {
		this.priority = priority;
	}
	
	public void run() {
		System.out.print(name);
	}
	
	public int getPriority() {
		return priority;
	}
	
	public void setDelay(long delayedMilliseconds) {
		this.delayedMilliseconds = System.nanoTime() + NANOSECONDS.convert(delayedMilliseconds, MILLISECONDS);
	}

	/* (non-Javadoc)
	 * @see java.util.concurrent.Delayed#getDelay(java.util.concurrent.TimeUnit)
	 */
	public long getDelay(TimeUnit unit) {
		if (delayedMilliseconds == 0) return 0;
		return unit.convert(delayedMilliseconds - System.nanoTime(), NANOSECONDS);
	}

	/* (non-Javadoc)
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	public int compareTo(Delayed o) {
		RunTask that = (RunTask)o;
		if (this.delayedMilliseconds < that.delayedMilliseconds) {
			return -1;
		} else if (this.delayedMilliseconds > that.delayedMilliseconds) {
			return 1;
		} else {
			return   that.priority - priority;
		}
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}
	
	
}
